/*
 * Copyright 2012 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.google.android.gcm.demo.server;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Simple implementation of a data store using standard Java collections.
 * <p>
 * This class is thread-safe but not persistent (it will lost the data when the
 * app is restarted) - it is meant just as an example.
 */
public final class Datastore {

	private static final Map<String, List<String>> regIds = new HashMap<String, List<String>>();
	private static final Logger logger =
			Logger.getLogger(Datastore.class.getName());
	private static Tokens tokens = new Tokens();
	private static Map<String, String> devices = new HashMap<String, String>();

	private Datastore() {
		throw new UnsupportedOperationException();
	}

	/**
	 * Registers a device.
	 */
	public static void register(String regId, String deviceName) {
		logger.info("Registering " + regId);
		synchronized (regIds) {
			regIds.put(regId, new ArrayList<String>());
			devices.put(regId, deviceName);
		}
	}

	/**
	 * Unregisters a device.
	 */
	public static void unregister(String regId) {
		logger.info("Unregistering " + regId);
		synchronized (regIds) {
			regIds.remove(regId);
			devices.remove(regId);
		}
	}

	/**
	 * Updates the registration id of a device.
	 */
	public static void updateRegistration(String oldId, String newId) {
		logger.info("Updating " + oldId + " to " + newId);
		synchronized (regIds) {
			List<String> old = regIds.remove(oldId);
			regIds.put(newId, old);
			String oldDevice = devices.remove(oldId);
			devices.put(newId, oldDevice);
		}
	}

	/**
	 * Gets all registered devices.
	 */
	public static List<String> getDevices() {
		synchronized (regIds) {
			return new ArrayList<String>(regIds.keySet());
		}
	}
	
	public static String getDeviceName(String regId) {
		synchronized (regIds) {
			return devices.get(regId);
		}
	}

	public static Tokens getTokens() {
		return tokens;
	}

}
